﻿Imports System.Web.UI
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Configuration
Imports System.Net.Mail

Partial Public Class Wfrm_Genera_OrdenCompra
    Inherits System.Web.UI.Page
    Dim Ocs As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then
            ViewState("usuario") = Session("usuario")
            ViewState("usu") = Session("usuario")

            Anthem.Manager.Register(Me)
            Carga_Grilla_SOL()
            'Carga_Grilla_OC()
            FPago()
        End If
    End Sub
    Sub FPago()
       
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_GET_FPAGOS"

        exec.ExecuteDataTable(rp)
        cmb_forma_pago.DataTextField = "tdescripcion"
        cmb_forma_pago.DataValueField = "ncodigo_pki"
        cmb_forma_pago.DataSource = rp.DtTable
        cmb_forma_pago.DataBind()
        cmb_forma_pago.UpdateAfterCallBack = True


    End Sub
    Sub Carga_Grilla_OC()
        Dim Dt As New DataTable

        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_GET_ORDEN_COMPRA_GENERADA_DIA"
        exec.ExecuteDataTable(rp)
        If rp.TieneDatos Then
            Dt = rp.DtTable.Clone
        Else
            Dt = Nothing
        End If

        If Not Ocs Is Nothing Then
            If rp.TieneDatos Then
                Dim oc() As String
                oc = Ocs.Split(";")
                Dim j As Integer
                For j = 0 To oc.Length - 1
                    Dim i As Integer
                    For i = 0 To rp.DtTable.Rows.Count - 1
                        If rp.DtTable.Rows(i).Item("ID_ORDEN_COMPRA") = oc(j) Then
                            Dt.ImportRow(rp.DtTable.Rows(i))
                        End If
                    Next
                Next
            End If
        End If

        Grilla_OC.DataSource = Dt ' rp.DtTable
        Grilla_OC.DataBind()
        Grilla_OC.UpdateAfterCallBack = True


    End Sub
    Sub Carga_Grilla_SOL()
        '0 -- Id_Producto
        '9 -- Control de proveedores

        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_Get_Sol_OC"
        exec.ExecuteDataTable(rp)
        Grilla_SOL.DataSource = rp.DtTable
        Grilla_SOL.DataBind()
        Grilla_SOL.UpdateAfterCallBack = True

        'LOGICA DE SALDO A COMPRAR CON LO QUE SE GUARDO TEMPORAL
        'SI LO QUE ESTÁ EN LA CAJA DE TEXTO DE SALDO A COMPRAR ES CERO, SE ESCRIBE L ARESTA ENTRE SOLICITUD - COMPRADO
        Dim i As Integer
     
        For i = 0 To Me.Grilla_SOL.Items.Count - 1
            If rp.DtTable.Rows(i).Item(6) = "0" Then
                'DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).Text = FormatNumber(rp.DtTable.Rows(i).Item(4) - rp.DtTable.Rows(i).Item(5), 0) 'Val(Grilla_SOL.Items(i).Cells(6).Text) - Val(Grilla_SOL.Items(i).Cells(7).Text)
                DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True

                'le asigno la fila al boton grabar y al eliminar
                '<script></script> 
            End If

            'DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).Attributes.Add("onkeyup", "this.value =FormatNumber(this.value);")
            DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).Attributes.Add("onkeyup", "this.value=FormatNumber(this.value);")

            'Asignar mejor proveedor
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).Items.Clear()
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).DataSource = FuncionesGlobal.GetProveedorPrecio(exec, Grilla_SOL.Items(i).Cells(12).Text)
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).DataValueField = "tRUT_PK"
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).DataTextField = "tNombres"            
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).DataBind()
            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).UpdateAfterCallBack = True
            ' DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).ValidationGroup = DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).ID & "|" & i

            If rp.DtTable.Rows(i).Item("FK_PROVEEDOR_TEMP").ToString() <> "" Then

                Dim cmb As New DropDownList
                Dim k As Integer

                For k = 0 To DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).Items.Count - 1
                    If InStr(DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).Items(k).Value.Split(" ")(0), rp.DtTable.Rows(i).Item("FK_PROVEEDOR_TEMP")) > 0 Then
                        If InStr(DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).Items(k).Text, Val(rp.DtTable.Rows(i).Item("PRECIO_TEMP"))) > 0 Then
                            DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).Items(k).Selected = True
                            Exit For
                        End If

                    End If

                Next

                DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text = Val(rp.DtTable.Rows(i).Item("PRECIO_TEMP"))
                DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True

            Else
                'Precio
                Dim Precio As String = "$ 0"
                Try
                    Precio = DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedItem.Text
                Catch ex As Exception
                    Precio = "$ 0"
                End Try

                If Val(DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text) = 0 Then
                    Try
                        DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text = Precio.Split(" ")(1)
                    Catch ex As Exception
                        DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text = ""
                    End Try

                    DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True
                End If

            End If

            Dim script As String = "return confirm('¿Esta Seguro(a) de Eliminar el Producto de la Solicitud?');"
            DirectCast(Grilla_SOL.Items(i).Cells(2).Controls(1), Anthem.ImageButton).Attributes.Add("onclick", script)
            'Anthem.Manager.AddScriptForClientSideEval("$('" & DirectCast(Grilla_SOL.Items(i).Cells(2).Controls(1), Anthem.ImageButton).ClientID & "').bind('copy', function(){return false;});")
            'Anthem.Manager.AddScriptForClientSideEval("$('" & DirectCast(Grilla_SOL.Items(i).Cells(2).Controls(1), Anthem.ImageButton).ClientID & "').bind('paste', function(){return false;});")
            DirectCast(Grilla_SOL.Items(i).Cells(2).Controls(1), Anthem.ImageButton).CommandName = i
            'DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.ImageButton).CommandName = i
        Next
        exec.Commit()
        exec.Dispose()

    End Sub
    Protected Sub Aceptar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Try
            'Actualiza la solicitud .
            ' 0 Y 3
            Dim fila As Integer = DirectCast(sender.parent.parent, DataGridItem).ItemIndex
            Dim CANT_TEMP As Decimal

            Try
                CANT_TEMP = DirectCast(Grilla_SOL.Items(fila).Cells(8).Controls(1), Anthem.TextBox).Text
            Catch ex As Exception
                'no es un numero 
                Mensaje("Wfrm_Genera_OrdenCompra", "ValNumero")
                Exit Sub
            End Try


            'si la cantidad ingresada es mayor que el saldo que queda o menor que 1, se arroja un error
            If CANT_TEMP < 1 Then
                Mensaje("Wfrm_Genera_OrdenCompra", "ValCantidadMayorCero")
                Exit Sub
            End If
            If DirectCast(Grilla_SOL.Items(fila).Cells(7).Controls(1), Label).Text < CANT_TEMP Then
                DirectCast(Grilla_SOL.Items(fila).Cells(8).Controls(1), Anthem.TextBox).Text = DirectCast(Grilla_SOL.Items(fila).Cells(6).Controls(1), Label).Text - DirectCast(Grilla_SOL.Items(fila).Cells(7).Controls(1), Label).Text
                DirectCast(Grilla_SOL.Items(fila).Cells(8).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True
                Mensaje("Wfrm_Genera_OrdenCompra", "ValSaldo")
                Exit Sub
            End If


            Dim FK_SOLICITUD As String = Grilla_SOL.Items(fila).Cells(3).Text
            Dim FK_PROVEEDOR As String = DirectCast(Grilla_SOL.Items(fila).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue
            Dim FK_PRODUCTO As String = Grilla_SOL.Items(fila).Cells(12).Text
            Dim Precio As Decimal

            Try
                Precio = DirectCast(Grilla_SOL.Items(fila).Cells(10).Controls(1), Anthem.TextBox).Text
            Catch ex As Exception
                'no es un numero 
                Mensaje("Wfrm_Genera_OrdenCompra", "ValPrecio")
                Exit Sub
            End Try

            Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
            Dim rp As New DotNetResponse.SQLPersistence
            rp.StoredProcedure = "SP_OC_UPDATE_SOL_PROD_TEMP"
            rp.AddParametro(FK_SOLICITUD)
            rp.AddParametro(FK_PROVEEDOR)
            rp.AddParametro(FK_PRODUCTO)
            rp.AddParametro(ViewState("usu"))
            rp.AddParametro(CANT_TEMP)
            rp.AddParametro(Precio)
            exec.ExecuteNonQuery(rp)
            exec.Commit()

            ' rp.AddParametro(FK_SOLICITUD
            ',@FK_PROVEEDOR VARCHAR(20)
            ',@FK_PRODUCTO INT
            ',@FK_USUARIO VARCHAR(30)
            ',@CANT_TEMP NUMERIC(18,3)

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub img_crear_oc_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_crear_oc.Click
        Ocs = ""
        Dim i As Integer
        Dim ct As Integer = 0
        Dim dt As New DataTable
        dt.Columns.Add("proveedor") '.Unique = True
        dt.Columns.Add("clinica") '.Unique = True

        Dim keys(1) As DataColumn
        keys(0) = dt.Columns(0)
        keys(1) = dt.Columns(1)

        dt.PrimaryKey = keys

        For i = 0 To Grilla_SOL.Items.Count - 1
            If DirectCast(Grilla_SOL.Items(i).Cells(1).Controls(1), Anthem.CheckBox).Checked Then
                ct = ct + 1
                Try
                    Dim dr As DataRow
                    dr = dt.NewRow
                    dr(0) = DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue.Split(" ")(0)
                    dr(1) = Grilla_SOL.Items(i).Cells(4).Text.Trim
                    dt.Rows.Add(dr)
                Catch ex As Exception

                End Try
            End If
        Next

        If ct = 0 Then
            Mensaje("Debe seleccionar Solicitud")
            Exit Sub
        End If

        Dim FilaErro As Integer = 0
        Dim erro As Boolean = False

        Dim k As Integer
        Dim j As Integer
        For j = 0 To dt.Rows.Count - 1
            For k = 0 To Grilla_SOL.Items.Count - 1
                DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).BackColor = Drawing.Color.Transparent
                DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).UpdateAfterCallBack = True

                If DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).Checked And DirectCast(Grilla_SOL.Items(k).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue = dt.Rows(j).Item(0) And Grilla_SOL.Items(k).Cells(4).Text.Trim = dt.Rows(j).Item(1) Then
                    'Validar cant compra - cant disponible 
                    If Val(DirectCast(Grilla_SOL.Items(k).Cells(7).Controls(1), Label).Text.Replace(".", "").Replace(",", "")) < Val(DirectCast(Grilla_SOL.Items(k).Cells(8).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", "")) Then
                        'Grilla_SOL.Items(k).BorderColor = Drawing.Color.Red
                        'Grilla_SOL.Items(k).BorderWidth = 2
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).UpdateAfterCallBack = True

                        'Mensaje(
                        Grilla_SOL.UpdateAfterCallBack = True
                        erro = True
                    End If

                    If Not IsNumeric((DirectCast(Grilla_SOL.Items(k).Cells(10).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", ""))) Then
                        'Grilla_SOL.Items(k).BorderColor = Drawing.Color.Red
                        'Grilla_SOL.Items(k).BorderWidth = 2
                        'Grilla_SOL.Items(k).Cells(10).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).UpdateAfterCallBack = True
                        Grilla_SOL.UpdateAfterCallBack = True
                        erro = True
                    End If
                    If (DirectCast(Grilla_SOL.Items(k).Cells(10).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", "")) <= 0 Then
                        'Grilla_SOL.Items(k).BorderColor = Drawing.Color.Red
                        'Grilla_SOL.Items(k).BorderWidth = 2
                        'Grilla_SOL.Items(k).Cells(10).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).UpdateAfterCallBack = True
                        Grilla_SOL.UpdateAfterCallBack = True
                        erro = True
                    End If

                    If DirectCast(Grilla_SOL.Items(k).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue.ToString.Length = 0 Then
                        'Grilla_SOL.Items(k).BorderColor = Drawing.Color.Red
                        'Grilla_SOL.Items(k).BorderWidth = 2
                        'Grilla_SOL.Items(k).Cells(9).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).BackColor = Drawing.Color.Red
                        DirectCast(Grilla_SOL.Items(k).Cells(1).Controls(1), Anthem.CheckBox).UpdateAfterCallBack = True
                        Grilla_SOL.UpdateAfterCallBack = True
                        erro = True
                    End If

                End If
            Next
        Next
        If erro Then
            Mensaje("Existe un error , favor revisar sus datos ingresados")
            Exit Sub
        End If

        Dim EXEC As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        For j = 0 To dt.Rows.Count - 1

            'Dim EXEC As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
            
            Dim rp As New DotNetResponse.SQLPersistence
            rp.StoredProcedure = "SP_OC_INSERT_ORDEN_COMPRA"
            rp.AddParametro(dt.Rows(j).Item(0).ToString.Split(" ")(0))
            rp.AddParametro(ViewState("usuario"))
            rp.AddParametro(0)
            EXEC.ExecuteScalar(rp)

            Dim Id_Oc As String = rp.GetScalar

            If rp.Errores Then
                DotNetDal.Generica.AppendLogFile("Excepcion" & i.ToString & " : " & Now.ToString & " ..... " & rp.MensajeError, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")
                Mensaje("Existe un error , " & rp.MensajeError)
            End If

            DotNetDal.Generica.AppendLogFile("registro " & j.ToString & " : " & Now.ToString, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")

            If Ocs = "" Then
                Ocs = Id_Oc
            Else
                Ocs = Ocs & ";" & Id_Oc '17 07 2011
            End If


            For i = 0 To Grilla_SOL.Items.Count - 1

                DotNetDal.Generica.AppendLogFile("Producto  " & i.ToString & " : " & Now.ToString, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")

                If DirectCast(Grilla_SOL.Items(i).Cells(1).Controls(1), Anthem.CheckBox).Checked And DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue.Split(" ")(0) = dt.Rows(j).Item(0) And Grilla_SOL.Items(i).Cells(4).Text.Trim = dt.Rows(j).Item(1) Then
                    'Validar cant compra - cant disponible 
                    If (Grilla_SOL.Items(i).Cells(7).Text.Replace(".", "").Replace(",", "")) > DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", "") Then
                        FilaErro = i
                        Exit For
                    End If

                    Dim rpP As New DotNetResponse.SQLPersistence
                    rpP.StoredProcedure = "SP_OC_INSERT_ORDEN_COMPRA_PRODUCTO"
                    rpP.AddParametro(Id_Oc)
                    rpP.AddParametro(Grilla_SOL.Items(i).Cells(3).Text)
                    rpP.AddParametro(Grilla_SOL.Items(i).Cells(12).Text)
                    'cantidad 8
                    rpP.AddParametro(DirectCast(Grilla_SOL.Items(i).Cells(8).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", ""))
                    'precio 10
                    rpP.AddParametro(DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", ""))

                    rpP.AddParametro(ViewState("usuario"))
                    EXEC.ExecuteNonQuery(rpP)

                    If rpP.Errores Then
                        DotNetDal.Generica.AppendLogFile("Excepcion" & i.ToString & " : " & Now.ToString & " ..... " & rpP.MensajeError, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")
                        Mensaje("Existe un error , " & rpP.MensajeError)
                    End If
                    'Insertar Nuevo Precio si es distinto
                    Dim Precio As String
                    Try
                        Precio = DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedItem.Text.Split(" ")(1)
                    Catch ex As Exception
                        Precio = "$ 0"
                    End Try

                    If (Precio <> DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", "")) Then
                        'insertar Precio
                        Dim RPre As New DotNetResponse.SQLPersistence
                        RPre.AddParametro(Grilla_SOL.Items(i).Cells(12).Text)
                        RPre.AddParametro(DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedValue.Split(" ")(0))
                        RPre.AddParametro(DirectCast(Grilla_SOL.Items(i).Cells(10).Controls(1), Anthem.TextBox).Text.Replace(".", "").Replace(",", ""))
                        RPre.AddParametro(DirectCast(Grilla_SOL.Items(i).Cells(9).Controls(1), Anthem.DropDownList).SelectedItem.Text.Split("-")(1).Replace("x", "").Trim())
                        RPre.StoredProcedure = "SP_OC_INSERT_PRODUCTO_PRECIO"
                        EXEC.ExecuteNonQuery(RPre)

                        DotNetDal.Generica.AppendLogFile("Producto Precio  " & i.ToString & " : " & Now.ToString, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")

                        If RPre.Errores Then
                            DotNetDal.Generica.AppendLogFile("Excepcion" & i.ToString & " : " & Now.ToString & " ..... " & RPre.MensajeError, ConfigurationSettings.AppSettings("ruta_rpt") & "Log_creacion_OC_" & Id_Oc & ".txt")
                            Mensaje("Existe un error , " & RPre.MensajeError)
                        End If

                    End If

                End If




            Next

            If FilaErro > 0 Then
                EXEC.Rollback()
                Mensaje("Existe un error , favor revisar sus datos ingresados")
                Exit Sub
                Exit For
            End If
            'EXEC.Commit()

        Next
        EXEC.Commit()


        Carga_Grilla_SOL()
        Carga_Grilla_OC()

        Label2.Visible = True

        lbl_Observacion.Visible = False
        lbl_Observacion.UpdateAfterCallBack = True

        txt_observacion.Text = ""
        txt_observacion.Visible = False
        txt_observacion.UpdateAfterCallBack = True


        Label2.UpdateAfterCallBack = True
        Panel1.Visible = True
        Panel1.UpdateAfterCallBack = True

        img_imprimir.Visible = False
        img_Despachar.Visible = False
        img_Despachar.UpdateAfterCallBack = True
        img_imprimir.UpdateAfterCallBack = True


        lbl_proveedor.Text = ""
        lbl_nro_oc.Text = ""
        lbl_proveedor.UpdateAfterCallBack = True
        lbl_nro_oc.UpdateAfterCallBack = True

        Grilla_SOL0.DataSource = Nothing
        Grilla_SOL0.DataBind()
        Grilla_SOL0.UpdateAfterCallBack = True


        lblSolicitud1.Visible = False
        lblSolicitud6.Visible = False
        lblSolicitud1.UpdateAfterCallBack = True
        lblSolicitud6.UpdateAfterCallBack = True

    End Sub

    Protected Sub Eliminar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        '      SP_OC_DEL_PRODUCTO_SOLCIITUD()

        ' @FK_SOLICITUD NUMERIC(18,0)
        ',@FK_PRODUCTO INT
        Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_DEL_PRODUCTO_SOLCIITUD"
        rp.AddParametro(DirectCast(sender.parent.parent, DataGridItem).Cells(3).Text)
        rp.AddParametro(DirectCast(sender.parent.parent, DataGridItem).Cells(12).Text)
        exec.ExecuteNonQuery(rp)
        exec.Commit()

        If Not rp.Errores Then
            Carga_Grilla_SOL()
        End If



    End Sub
    Sub ColorCelda()

    End Sub

    Sub Mensaje(ByVal tbl As String, ByVal codigo As String)
        Dim mensaje As String = FuncionesGlobal.GetMensaje(tbl, codigo)
        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & mensaje & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & mensaje & "')</script>")
        End If

    End Sub
    Sub Mensaje(ByVal Msg As String)

        If Anthem.Manager.IsCallBack Then
            Anthem.Manager.AddScriptForClientSideEval("alert('" & Msg & "')")
        Else
            Page.ClientScript.RegisterStartupScript(Me.GetType, "alertar", "<script>alert('" & Msg & "')</script>")
        End If

    End Sub
    Protected Sub Cmb_Proveedor_SelectedIndexChanged1(ByVal sender As Object, ByVal e As EventArgs)

        Dim Precio As String
        Try
            Precio = DirectCast(sender, Anthem.DropDownList).SelectedItem.Text.Split(" ")(1)
        Catch ex As Exception
            Precio = "{$ 0 }"
        End Try


        Dim i As Integer
        DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).Text = Precio
        DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).ValidationGroup = Precio
        DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True

    End Sub


    Protected Sub txt_Precio_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsNumeric(DirectCast(sender, Anthem.TextBox).Text) Then
            Dim Precio As String
            Try
                Precio = DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(9).Controls(1), Anthem.DropDownList).SelectedItem.Text
            Catch ex As Exception
                Precio = "{$ 0 }"
            End Try

            DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).Text = Precio.Split(" ")(1)
        End If

        DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).Text = FormatNumber(DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).Text, 0)
        DirectCast(DirectCast(sender.parent.parent, DataGridItem).Cells(10).Controls(1), Anthem.TextBox).UpdateAfterCallBack = True
    End Sub

    Protected Sub lnk_despachar_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim script As String = "  myLightWindow.activateWindow({"
        script = script & " href:   '" & "Wfrm_Despacha_OrdenCompra.aspx" & "?id_oc=" & DirectCast(sender.parent.parent, DataGridItem).Cells(3).Text & "', "
        script = script & " title:  '" & "Despacho de Orden De Compra" & "', "
        script = script & " author:  'JQUINTANILLA', "
        script = script & " caption:  '', "
        script = script & "  left: 500,"
        script = script & "  width: 800,"
        script = script & "  height: 500,"
        script = script & "  top: 300"
        script = script & " });"

        Anthem.Manager.AddScriptForClientSideEval(script)

    End Sub

    Protected Sub Eliminar0_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Dim exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_OC_DEL_ORDEN_COMPRA"
        rp.AddParametro(DirectCast(sender.parent.parent, DataGridItem).Cells(3).Text)
        exec.ExecuteNonQuery(rp)
        exec.Commit()

        If Not rp.Errores Then
            Carga_Grilla_OC()
            Carga_Grilla_SOL()
        End If

        img_imprimir.Visible = False
        img_Despachar.Visible = False
        img_Despachar.UpdateAfterCallBack = True
        img_imprimir.UpdateAfterCallBack = True

        lbl_proveedor.Text = ""
        lbl_nro_oc.Text = ""
        lbl_proveedor.UpdateAfterCallBack = True
        lbl_nro_oc.UpdateAfterCallBack = True

        Grilla_SOL0.DataSource = Nothing
        Grilla_SOL0.DataBind()
        Grilla_SOL0.UpdateAfterCallBack = True

    End Sub

    Protected Sub Grilla_OC_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Grilla_OC.SelectedIndexChanged
        lbl_proveedor.Text = Grilla_OC.SelectedItem.Cells(4).Text
        lbl_proveedor.UpdateAfterCallBack = True
        lbl_nro_oc.Text = Grilla_OC.SelectedItem.Cells(3).Text
        lbl_nro_oc.UpdateAfterCallBack = True


        Carga_Productos(Grilla_OC.SelectedItem.Cells(3).Text)

        lbl_Observacion.Visible = True
        lbl_Observacion.UpdateAfterCallBack = True

        txt_observacion.Text = ""
        txt_observacion.Visible = True
        txt_observacion.UpdateAfterCallBack = True


        img_Despachar.Visible = True
        img_imprimir.Visible = True
        img_imprimir.UpdateAfterCallBack = True
        img_Despachar.UpdateAfterCallBack = True
        lblSolicitud1.Visible = True
        lblSolicitud6.Visible = True
        lblSolicitud1.UpdateAfterCallBack = True
        lblSolicitud6.UpdateAfterCallBack = True

        datepicker.Text = ""
        lblfecha.Visible = True
        datepicker.Visible = True
        lblformaPago.Visible = True
        cmb_forma_pago.Visible = True

        lblfecha.UpdateAfterCallBack = True
        datepicker.UpdateAfterCallBack = True
        lblformaPago.UpdateAfterCallBack = True
        cmb_forma_pago.UpdateAfterCallBack = True


        'Buscar Forma de Pago del proveedor
        Try
            cmb_forma_pago.SelectedValue = Val(Grilla_OC.SelectedItem.Cells(7).Text)
        Catch ex As Exception

        End Try


        Anthem.Manager.AddScriptForClientSideEval(" $('#datepicker').datepicker({ changeYear: true, changeMonth: true });")

    End Sub
    Sub Carga_Productos(ByVal id_oc As String)
        Dim exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim rp As New DotNetResponse.SQLPersistence
        rp.StoredProcedure = "SP_GET_PRODUCTOS_ORDEN_COMPRA"
        rp.AddParametro(id_oc)
        exec.ExecuteDataTable(rp)
        Grilla_SOL0.DataSource = rp.DtTable
        Grilla_SOL0.DataBind()
        Grilla_SOL0.UpdateAfterCallBack = True
    End Sub

    Protected Sub img_imprimir_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_imprimir.Click
        If Not aCTUALIZA_dESPACHO() Then

            Exit Sub
        End If

        Dim rp As New Rpt_OrdenCompra

        Dim _CRConnectionInfo As ConnectionInfo

        _CRConnectionInfo = New ConnectionInfo()
        _CRConnectionInfo.ServerName = ConfigurationManager.AppSettings("cnn_server") '"application.dyndns-web.com"
        _CRConnectionInfo.DatabaseName = ConfigurationManager.AppSettings("cnn_database") '"comprasFarm"
        _CRConnectionInfo.UserID = ConfigurationManager.AppSettings("cnn_userid") '"lilas"
        _CRConnectionInfo.Password = ConfigurationManager.AppSettings("cnn_password") '"lilas"

        Dim tables As Tables
        tables = rp.Database.Tables
        For i = 0 To tables.Count - 1
            Dim tableLogonInfo As TableLogOnInfo = tables(i).LogOnInfo
            tableLogonInfo.ConnectionInfo = _CRConnectionInfo
            tables(i).ApplyLogOnInfo(tableLogonInfo)
        Next

        rp.SetParameterValue(0, lbl_nro_oc.Text)
        'rp.SetParameterValue(1, lbl_nro_oc.Text)


        'Dim tables2 As Tables
        'tables2 = rp.Subreports(0).Database.Tables
        'For i = 0 To tables2.Count - 1
        '    Dim tableLogonInfo As TableLogOnInfo = tables2(i).LogOnInfo
        '    tableLogonInfo.ConnectionInfo = _CRConnectionInfo
        '    tables2(i).ApplyLogOnInfo(tableLogonInfo)
        'Next

        'rp.Subreports(0).SetParameterValue("@OC_1", ViewState("id_oc"))
        'rp.Subreports(0).SetParameterValue(0, 17)
        DESPACHO_DB(lbl_nro_oc.Text)

        rp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Page.Response, True, "OrdenCompra_" & lbl_nro_oc.Text & ".pdf")
        'rp.ExportToDisk (ExportFormatType.PortableDocFormat ,"")

    End Sub
    Function aCTUALIZA_dESPACHO()
        'If Not IsDate(datepicker.Text) Then
        '    Mensaje("Falta ingresar Fecha Despacho")
        '    Return False
        'End If

        Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim RpE As New DotNetResponse.SQLPersistence
        RpE.StoredProcedure = "SP_OC_UPDATE_OC_DESPACHO"
        RpE.AddParametro(lbl_nro_oc.Text)
        RpE.AddParametro(datepicker.Text)
        RpE.AddParametro(cmb_forma_pago.SelectedValue)
        RpE.AddParametro(txt_observacion.Text.Trim)

        Exec.ExecuteNonQuery(RpE)
        Exec.Commit()

        Return True

    End Function
    Sub DESPACHO_DB(ByVal ID_OC As String)
        Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim RpE As New DotNetResponse.SQLPersistence
        RpE.StoredProcedure = "SP_OC_UPDATE_ENVIAR_OC"
        RpE.AddParametro(ID_OC)
        Exec.ExecuteNonQuery(RpE)
        Exec.Commit()

        If Not RpE.Errores Then
            'OCULTAR los objetos CERO y UNO
            Dim i As Integer
            For i = 0 To Grilla_OC.Items.Count - 1
                If Grilla_OC.Items(i).Cells(3).Text = ID_OC Then
                    DirectCast(Grilla_OC.Items(i).Cells(1).Controls(1), Anthem.ImageButton).Enabled = False
                    DirectCast(Grilla_OC.Items(i).Cells(1).Controls(1), Anthem.ImageButton).UpdateAfterCallBack = True
                    Exit For
                End If
            Next

            Grilla_OC.UpdateAfterCallBack = True
        Else
            Mensaje(RpE.MensajeError)

        End If
    End Sub


    Protected Sub img_Despachar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_Despachar.Click
        If Not aCTUALIZA_dESPACHO() Then

            Exit Sub
        End If


        lblSolicitud2.Text = "N° Orden de Compra : " & Grilla_OC.SelectedItem.Cells(3).Text
        lblSolicitud2.UpdateAfterCallBack = True

        Cargar_Datos_Despacho()

        txt_asunto.Text = "OC N° " & Grilla_OC.SelectedItem.Cells(3).Text
        txt_mensaje.Text = "Se adjunta detalle de Orden de Compra. Favor confirmar recepción y fecha de despacho."
        txt_asunto.UpdateAfterCallBack = True
        txt_mensaje.UpdateAfterCallBack = True

        Anthem.Manager.AddScriptForClientSideEval("document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'")

    End Sub
    Sub Cargar_Datos_Despacho()
        Dim Exec As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Rp.StoredProcedure = "SP_OC_GET_Datos_Despacho"
        Rp.AddParametro(Grilla_OC.SelectedItem.Cells(6).Text)
        Exec.ExecuteDataTable(Rp)
        If Rp.TieneDatos Then
            txt_asunto.Text = Rp.DtTable.Rows(0).Item("Subject")
            txt_destinatario.Text = Rp.DtTable.Rows(0).Item("email_destinatario")
            txt_destinatario.UpdateAfterCallBack = True

            txt_mensaje.Text = Rp.DtTable.Rows(0).Item("Body")
        End If


    End Sub
    Protected Sub img_Despachar0_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles img_Despachar0.Click



        Try
            Dim emails() As String = txt_destinatario.Text.Trim.Split(",")
            Dim ii As Integer
            For ii = 0 To emails.Length - 1
                If Not DotNetDal.Generica.ValidaEmail(emails(ii)) Then
                    Mensaje("Email inválido : " & emails(ii))
                    Exit Sub
                End If
            Next


            Dim Ruta_PDF As String = ConfigurationManager.AppSettings("ruta_rpt") & "OrdenCompra_" & lbl_nro_oc.Text & ".pdf"

            'If Not DotNetDal.Generica.ValidaEmail(txt_destinatario.Text.Trim) Then
            '    Mensaje("Email inválido")
            '    Exit Sub
            'End If

            Dim rep As New Rpt_OrdenCompra
            Dim _CRConnectionInfo As ConnectionInfo

            _CRConnectionInfo = New ConnectionInfo()
            _CRConnectionInfo.ServerName = ConfigurationManager.AppSettings("cnn_server") '"application.dyndns-web.com"
            _CRConnectionInfo.DatabaseName = ConfigurationManager.AppSettings("cnn_database") '"comprasFarm"
            _CRConnectionInfo.UserID = ConfigurationManager.AppSettings("cnn_userid") '"lilas"
            _CRConnectionInfo.Password = ConfigurationManager.AppSettings("cnn_password") '"lilas"

            Dim tables As Tables
            tables = rep.Database.Tables
            For i = 0 To tables.Count - 1
                Dim tableLogonInfo As TableLogOnInfo = tables(i).LogOnInfo
                tableLogonInfo.ConnectionInfo = _CRConnectionInfo
                tables(i).ApplyLogOnInfo(tableLogonInfo)
            Next

            rep.SetParameterValue(0, lbl_nro_oc.Text)
            'rep.SetParameterValue(1, lbl_nro_oc.Text)

            'Dim tables2 As Tables
            'tables2 = rep.Subreports(0).Database.Tables
            'For i = 0 To tables2.Count - 1
            '    Dim tableLogonInfo As TableLogOnInfo = tables2(i).LogOnInfo
            '    tableLogonInfo.ConnectionInfo = _CRConnectionInfo
            '    tables2(i).ApplyLogOnInfo(tableLogonInfo)
            'Next

            'rp.Subreports(0).SetParameterValue("@OC_1", ViewState("id_oc"))
            'rp.Subreports(0).SetParameterValue(0, 17)
            Dim Rp As New DotNetResponse.SQLPersistence
            Dim Exec As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)

            Dim EmailCC As String = ""

            Rp.StoredProcedure = "SP_GET_EMAIL_CLINICA"
            Rp.AddParametro(Val(lbl_nro_oc.Text))
            Exec.ExecuteDataTable(Rp)
            If Not Rp.TieneDatos Then
                Mensaje("OC no encontrada")
                Exec.Rollback()
                Exit Sub
            Else
                If Rp.DtTable.Rows(0).Item(0).ToString.Length = 0 Then
                    Mensaje("Email no registrado")
                    Exec.Rollback()
                    Exit Sub
                Else
                    If Not DotNetDal.Generica.ValidaEmail(Rp.DtTable.Rows(0).Item(0).ToString) Then
                        Mensaje("Email inválido : " & Rp.DtTable.Rows(0).Item(0).ToString)
                        Exit Sub
                    End If
                End If
            End If
            EmailCC = Rp.DtTable.Rows(0).Item(0).ToString
            txt_asunto.Text = Rp.DtTable.Rows(0).Item(1).ToString() & " " & txt_asunto.Text.Trim


            'rp.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Page.Response, True, "OrdenCompra_" & Grilla_OC.SelectedItem.Cells(3).Text & ".pdf")
            If IO.File.Exists(Ruta_PDF) Then
                'enviar email
                'For ii = 0 To emails.Length - 1
                SendMail(Rp, txt_destinatario.Text.Trim, txt_mensaje.Text.Trim, txt_asunto.Text.Trim, Ruta_PDF, ConfigurationManager.AppSettings("mail_CC") & "," & EmailCC)
                'Next
                If Rp.Errores Then
                    Mensaje(Rp.MensajeError)
                    Exec.Rollback()
                    Exit Sub
                End If

                'SendMail(Rp, txt_destinatario.Text.Trim, txt_mensaje.Text.Trim, txt_asunto.Text.Trim, Ruta_PDF)
                Anthem.Manager.AddScriptForClientSideEval("document.getElementById('light').style.display='hidden';document.getElementById('fade').style.display='hidden'")
                Mensaje("Orden de Compra Despachada Exitosamente")
                Exit Sub
            Else
                rep.ExportToDisk(ExportFormatType.PortableDocFormat, Ruta_PDF)

            End If

            Rp.ClearParametro()
            Rp.StoredProcedure = "SP_OC_SAVE_Datos_Despacho"
            Rp.AddParametro(Grilla_OC.SelectedItem.Cells(6).Text)
            Rp.AddParametro(txt_asunto.Text.Trim)
            Rp.AddParametro(txt_destinatario.Text.Trim)
            Rp.AddParametro(txt_mensaje.Text.Trim)
            Exec.ExecuteNonQuery(Rp)


            If Rp.Errores Then
                Mensaje(Rp.MensajeError)
                Exec.Rollback()
                Exit Sub
            Else
                'enviar email
                'enviar email
                SendMail(Rp, txt_destinatario.Text.Trim, txt_mensaje.Text.Trim, txt_asunto.Text.Trim, Ruta_PDF, ConfigurationManager.AppSettings("mail_CC") & "," & EmailCC)
                'SendMail(Rp, txt_destinatario.Text.Trim, txt_mensaje.Text.Trim, txt_asunto.Text.Trim, Ruta_PDF)
            End If

            If Rp.Errores Then
                Mensaje(Rp.MensajeError)
                Exec.Rollback()
                Exit Sub
            End If

            Exec.Commit()
            DESPACHO_DB(lbl_nro_oc.Text)

            ' Anthem.Manager.AddScriptForClientSideEval("document.getElementById('light').style.display='hidden';document.getElementById('fade').style.display='hidden'")

            Mensaje("Orden de Compra Despachada Exitosamente")

        Catch ex As Exception
            Mensaje(ex.Message)
        End Try
    End Sub
    Sub SendMail(ByRef rp As DotNetResponse.SQLPersistence, ByVal mail_destino As String, ByVal Body As String, ByVal subject As String, ByVal Archivo As String, ByVal CC As String)
        Try
            Dim Mail As MailMessage
            Dim SmtpServer As New SmtpClient()
            SmtpServer.Credentials = New Net.NetworkCredential(ConfigurationManager.AppSettings("mail_credencial_login"), ConfigurationManager.AppSettings("mail_credencial_clave")) 'WebConfig
            SmtpServer.Port = 25
            SmtpServer.Host = ConfigurationManager.AppSettings("mail_credencial_servidor")
            'SmtpServer.EnableSsl = True
            Mail = New MailMessage()
            Try
                Mail.From = New MailAddress(ConfigurationManager.AppSettings("mail_email_origen"), ConfigurationManager.AppSettings("mail_nombre_origen"), System.Text.Encoding.UTF8) 'WebConfig
                Mail.Subject = subject
                If Archivo.Length > 0 Then
                    Dim item As New System.Net.Mail.Attachment(Archivo)
                    Mail.Attachments.Add(item)
                End If
                Mail.To.Add(mail_destino)

                If Not CC Is Nothing Then
                    Mail.CC.Add(CC)
                End If

                Mail.Body = Body

                SmtpServer.Send(Mail)
            Catch ex As Exception
                rp.Errores = True
                rp.MensajeError = ex.Message
            End Try

        Catch ex As Exception
            rp.Errores = True
            rp.MensajeError = ex.Message
        End Try

    End Sub
End Class